import __config from '../config'
import { SESSION } from '../constant'
import es6 from '../lib/es6-promise'

class Util{
	constructor() {
	}

	/**
	 * 获取session方法，返回resolve值为为session的Promise
	 */
	__hasLocalSession(){
		return new es6.Promise((resolve, reject) => {
				const res = wx.getStorageInfoSync()
				let hasSession = false,
					session = ''
				if(res.keys && res.keys.length > 0 && res.keys.indexOf(SESSION) > -1){
					hasSession = true
					session = wx.getStorageSync(SESSION)
				}

				if(hasSession){
					resolve(session)
				} else {
					resolve(false)
				}
		})
	}

	__loginForCode(){
		return new es6.Promise((resolve, reject) => {
			wx.login({
				success(res){
					resolve(res.code)
				},
				fail(e){
					reject(e)
				}
			})
		})
	}

	__codeForSession(code){
		return new es6.Promise((resolve, reject) => {
			wx.request({
				url: `${__config.baseUrl}/index.php`,
				data: {code: code},
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				method: 'POST',
				success(data){
					let response = data.data
					if(response && typeof response === 'string'){
						response = JSON.parse(response)
					}
					wx.setStorageSync(SESSION, response.data.session)
					resolve(response.data.session)
				},
				fail(e){
					reject(e)
				}
			})
		})
	}

	__requestForSession(){
		return new es6.Promise((resolve, reject) => {
			this.__loginForCode()
			.then(code => {
				return this.__codeForSession(code)
			})
			.then(session => {
				resolve(session)
			})
			.catch(e => {
				reject(e)
			})
		})
	}

	__checkSession(session){
		return new es6.Promise((resolve, reject) => {
			wx.checkSession({
				success(){
					resolve(session)
				},
				fail(){
					resolve(false)
				}
			})
		})
	}

	getSession(){
		return new es6.Promise((resolve, reject) => {
			this.__hasLocalSession()
			.then(result => {
				if(result){
					return es6.Promise.resolve(result)
				} else {
					return this.__requestForSession()
				}
			})
			.then(session => {
				return this.__checkSession(session)
			})
			.then(result => {
				if(result){
					return es6.Promise.resolve(result)
				} else {
					return this.__requestForSession()
				}
			})
			.then(session => {
				resolve(session)
			})
			.catch(e => {
				reject(e)
			})
		})
	}

	/**
	 * [showTip] 消息toast
	 * @method showTip
	 * @param  {Object} that   [页面作用域]
	 * @param  {String} txt    [toast的文本消息]
	 * @param  {Number} period [toast展示时间]
	 */
	showTip(that, txt, period = 400) {
	  period = Number(period) || 400
	  if (typeof txt != 'string' || !txt) return
	  that.setData({
	    showTipTxt: txt,
	    tipHidden: false
	  })
	  setTimeout(() => {
	    that.setData({
	      showTipTxt: '',
	      tipHidden: true
	    })
	  }, period)
	}
}

export default Util
